package cn.com.dashihui.web.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

import cn.com.dashihui.web.dao.Baby;
import cn.com.dashihui.web.dao.BabyTitle;
import cn.com.dashihui.web.dao.GoodsEge;

public class BabyService {
	public boolean sortAd(Map<String,String> sortMap){
		int batchSize = sortMap.size();
		List<String> sqlList = new ArrayList<String>();
		for(String id : sortMap.keySet()){
			sqlList.add("UPDATE t_bus_goods_base_baby SET orderNo="+sortMap.get(id)+" WHERE id="+id);
		}
		int[] result = Db.batch(sqlList,batchSize);
		return result.length>0;
	}
	
	public List<Baby> findAll(){
		return Baby.me().find("SELECT sa.*,sg.name goodsName FROM t_bus_goods_base_baby sa LEFT JOIN t_bus_goods sg ON sa.goodsid=sg.id ORDER BY sa.orderNo");
	}
	
	public boolean addAd(Baby newObject){
		return newObject.save();
	}
	
	public boolean delAd(int id){
		return Baby.me().deleteById(id);
	}
	
	public boolean editAd(Baby object){
		return object.update();
	}
	
	public Baby findById(int id){
		return Baby.me().findFirst("SELECT sa.*,sg.name goodsName FROM t_bus_goods_base_baby sa LEFT JOIN t_bus_goods sg ON sa.goodsid=sg.id WHERE sa.id=?",id);
	}
	
	/**
	 * 查询兑换商品列表
	 * @param sGoodId
	 * @param sCategoryonid
	 * @param sCategorytwid
	 * @param keyword
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public Page<GoodsEge> getGoodsEge(int sGoodId,int sCategoryonid, int sCategorytwid,  String keyword,int pageNum, int pageSize) {
		StringBuffer sqlExcept = new StringBuffer("FROM t_bus_ege_goods AS A  LEFT JOIN t_dict_category D on A.categoryonid=D.categoryId LEFT JOIN t_dict_category E on A.categorytwid=E.categoryId where A.pstate !=3 and A.state=2");
		List<Object> params = new ArrayList<Object>();
		if(sGoodId!=0){
			sqlExcept.append(" AND A.id=?");
			params.add(sGoodId);
		}
		 if(sCategorytwid!=0){
			 sqlExcept.append(" AND A.categoryonid=? AND A.categorytwid=?");
			params.add(sCategoryonid);params.add(sCategorytwid);
		}else if(sCategoryonid!=0){
			sqlExcept.append(" AND A.categoryonid=?");
			params.add(sCategoryonid);
		}
		 if(!StrKit.isBlank(keyword)){
			sqlExcept.append(" AND A.name LIKE ?");
			params.add("%"+keyword+"%");
		}
		 sqlExcept.append(" group by A.id");
		return GoodsEge.me().paginate(pageNum, pageSize, "SELECT  A.* ", sqlExcept.toString(), params.toArray());
	}

	public BabyTitle findBabyTitle() {
		return BabyTitle.me().findFirst("select * from t_bus_goods_base_baby_title");
	}

	public BabyTitle findBabyTitleById(int id) {
		return BabyTitle.me().findFirst("select * from t_bus_goods_base_baby_title where id=?",id);
	}

}
